package com.nopay.dxdwphone.crash;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.blankj.utilcode.util.AppUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.NonNull;

import com.nopay.dxdwphone.Constants;

/**
 * 全局崩溃记录
 * @author 安琪
 * @since 全局单例模式
 */

public final class ExceptionHandler implements UncaughtExceptionHandler {
	private static final String TAG = "ExceptionHandler";
	private static String PATH_CRASH;
	private String mCrashLogPath;
	private static final boolean EASY_READ = true; // 打开的话\n会被替换成\r\n，方便windows同学打开阅读，OOM时候可能没内存操作，全面发布关闭
	private SimpleDateFormat mDateFormat;
	@NonNull
    private static StringBuilder logBuilder = new StringBuilder(2 * 1024);
	private Context mContext;
	public ExceptionHandler(@NonNull Context context) {
		mContext = context;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
			PATH_CRASH = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + File.separator + Constants.HOME_DIR + File.separator + Constants.CRASH_DIR;
		} else {// 如果SD卡不存在，就保存到本应用的目录下
			PATH_CRASH = context.getFilesDir().getAbsolutePath()
					+ File.separator + Constants.HOME_DIR + File.separator + Constants.CRASH_DIR;
		}
		File file = new File(PATH_CRASH);
		if (!file.exists()) {
			file.mkdirs();
		}
		mCrashLogPath = PATH_CRASH;
		mDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.CHINA);
	}

	@Override
	public void uncaughtException(Thread thread, @NonNull Throwable ex) {
		try {
			System.gc();
			Thread.sleep(1000);
			String logString = throwable2String(ex);
			saveErrorLog(logString);
		} catch (Throwable e) {
			// amen
		}
/*		PendingIntent restartIntent = null;
		if (android.text.TextUtils.isEmpty(SPUtils.getInstance().getString(AppConstants.SP_USERNAME))){//未登录
			Intent intent = new Intent(mContext, LoginActivity.class);
			restartIntent = PendingIntent.getActivity(mContext, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
		}else{//已登录
			Intent intent = new Intent(mContext, MainActivity.class);
			restartIntent = PendingIntent.getActivity(mContext, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
		}

		//退出程序
		AlarmManager mgr = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
				restartIntent); // 1秒钟后重启应用*/
		//关闭全部进程
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	private void saveErrorLog(String log) {
		
		String path = mCrashLogPath + File.separator + mDateFormat.format(new Date()) + "_AppVersionCode" + AppUtils.getAppVersionCode()  + ".txt";

		if (EASY_READ) {
			log = log.replaceAll("\n", "\r\n");
		}

		final String splitter;
		if (EASY_READ) {
			splitter = "\r\n";
		} else {
			splitter = "\n";
		}

		try {
			logBuilder.append(splitter).append(log);
		} catch (Throwable e) {
			// ...
		}

		try {
			FileOutputStream fos = new FileOutputStream(new File(path));
			try {
				writeString(fos, logBuilder.toString());
			} finally {
				fos.close();
			}

			logBuilder.delete(0, logBuilder.length());
		} catch (Throwable e) {
			// OMG，kill me！
		}
	}

	private String throwable2String(@NonNull final Throwable tr) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			tr.printStackTrace(pw);
			Log.e(TAG, sw.toString());
			return sw.toString();
		} catch (Throwable e) {
		}
		return "No Memory, throwable2String failed";
	}

	private void writeString(OutputStream out, String s) throws IOException {
		out.write(s.getBytes());
		out.flush();
	}
}
